import { login, logout, getInfo } from '@/api/login/user'
import { getUserInfo, getGiteeInfo } from '@/api/login/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { faceSearch } from '@/api/face/face'
import { encrypt } from '@/utils/sm2'

// vuex 变量存储
const state = {
  token: getToken(),
  // 用户信息
  user: {},
  // 存放权限信息
  roles: [],
  // 存放权限标识
  permissions: []
}

// vuex 设置变量信息
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  /**
   * 用户登陆方法
   * @param {*} param0 vuex路径
   * @param {*} userInfo 带来的请求参数
   * @returns
   */
  login({ commit }, userInfo) {
    const { username, password, params } = userInfo
    return new Promise((resolve, reject) => {
      const loginForm = {
        'username': username,
        'password': encrypt(password),
        'params': {
          'code': params.code,
          'randStr': params.randStr,
          'token': params.token,
          'randomStr': params.randomStr,
          'captchaType': params.captchaType || 'ISNUll'
        }
      }
      login(loginForm).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const data = response
        data.user.password = ''
        // 设置数据到 vuex 当中
        commit('SET_USER', data.user)
        // 判断是否是管理员权限
        if (data.user.isAdmin === 1) {
          // 管理员
          commit('SET_ROLES', ['admin'])
          commit('SET_PERMISSIONS', ['*:*:*'])
        } else {
          // 用户
          commit('SET_ROLES', data.permissions)
          commit('SET_PERMISSIONS', data.permissions)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // QQ登录成功后获取用户信息
  getUserInfo({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      getUserInfo(userInfo).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        // 刷新路由
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // GITEE登录成功后获取用户信息
  getGiteeInfo({ commit }, userInfo) {
    const { code } = userInfo
    return new Promise((resolve, reject) => {
      getGiteeInfo(code).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        // 刷新路由
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 人脸识别登录
  faceSearch({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      faceSearch(userInfo).then(response => {
        const { token } = response
        commit('SET_TOKEN', token)
        setToken(token)
        // 刷新路由
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 用户退出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER', {})
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        localStorage.clear()
        sessionStorage.clear()
        // 删除token
        removeToken()
        // 刷新路由
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
